<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { userLogin, doctorLogin } from '@/apis/accountAPI'
import { useAuthStore } from '@/stores/auth'
import { useUserStore } from '@/stores/user'
import { useDoctorStore } from '@/stores/doctor'
import { getDoctorProfile } from '@/apis/doctor/doctorProfileAPI'

interface LoginForm {
  phone: string
  password: string
  rememberAccount: boolean
  rememberPassword: boolean
  userType: 'doctor' | 'user'
}

const loginForm = reactive<LoginForm>({
  phone: '',
  password: '',
  rememberAccount: false,
  rememberPassword: false,
  userType: 'user'
})

const rules = {
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const loginFormRef = ref()
const router = useRouter()
const loading = ref(false)
const authStore = useAuthStore()
const userStore = useUserStore()
const doctorStore = useDoctorStore()

// 登录页面加载时不再从localStorage获取账号密码
// 所有用户信息将只存储在Pinia store中
onMounted(() => {
  // 页面初始化逻辑
})

const handleLogin = async () => {
  if (!loginFormRef.value) return
  await loginFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        // 根据用户类型调用不同的登录接口
        if (loginForm.userType === 'user') {
          const res = await userLogin({
            phone: loginForm.phone,
            password: loginForm.password
          })
          ElMessage.success('用户登录成功')
          // 保存登录状态和用户信息到store
          // 确保token存在且格式正确
          if (!res.data || !res.data.token) {
            throw new Error('登录失败：未获取到有效的token')
          }
          authStore.setUserInfo({
            ...res.data,
            token: res.data.token
          })
          authStore.setUserType('user')

          // 保存用户详细信息到user store
          userStore.setUserInfo({
            userId: res.data.id,
            username: res.data.name || '',
            nickname: res.data.nickname || '',
            avatar: res.data.avatar || ''
          })

          // 跳转到用户首页
          router.push('/user/overview')
        } else {
          const res = await doctorLogin({
            phone: loginForm.phone,
            password: loginForm.password
          })
          ElMessage.success('医生登录成功')
          // 保存登录状态和用户信息到store
          // 确保token存在且格式正确
          if (!res.data || !res.data.token) {
            throw new Error('登录失败：未获取到有效的token')
          }
          authStore.setUserInfo({
            ...res.data,
            token: res.data.token
          })
          authStore.setUserType('doctor')

          // 保存医生详细信息到doctor store
          doctorStore.setDoctorInfo({
            doctorId: res.data.id,
            name: res.data.name || '',
            title: res.data.title || '',
            department: res.data.department || '',
            hospital: res.data.hospital || '',
            avatar: res.data.avatar || ''
          })

          // 获取医生详细信息
          try {
            const profileRes = await getDoctorProfile()
            if (profileRes.status === 200 && profileRes.data) {
              doctorStore.setDoctorInfo(profileRes.data)
            }
          } catch (error) {
            console.error('获取医生详细信息失败', error)
          }

          // 跳转到医生首页
          router.push('/doctor/overview')
        }

        // 不再使用localStorage存储账号密码
        // 用户信息和token已经存储在Pinia store中，并通过persist选项自动持久化
      } catch (error: any) {
        ElMessage.error(error.message || '登录失败，请检查账号密码')
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<template>
  <div class="login-container">
    <div class="background-section">
      <div class="logo">logo</div>
      <div class="background-image">背景图</div>
    </div>
    <div class="form-section">
      <div class="form-content">
        <div class="form-title">登录</div>
        <div class="user-type-select">
          <el-radio-group v-model="loginForm.userType">
            <el-radio-button label="user">用户端</el-radio-button>
            <el-radio-button label="doctor">医生端</el-radio-button>
          </el-radio-group>
        </div>
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="rules"
          label-position="top"
          class="login-form"
        >
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="loginForm.phone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
            />
          </el-form-item>
          <div class="remember-options">
            <el-checkbox v-model="loginForm.rememberAccount">记住账号</el-checkbox>
            <el-checkbox v-model="loginForm.rememberPassword">记住密码</el-checkbox>
          </div>
          <el-form-item>
            <el-button type="primary" class="login-button" :loading="loading" @click="handleLogin">登录</el-button>
            <el-button class="register-button" @click="router.push('/register')">注册</el-button>
          </el-form-item>
        </el-form>
        <div class="copyright">Copyright @ 2025 HUCM-OpenLabs. All Rights Reserved</div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.background-image{
  background-image: "url('@/assets/')";
}

.login-container {
  display: flex;
  height: 100vh;
  width: 100vw;
  background-color: #f5f7fa;
}

.background-section {
  flex: 1;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
  border-radius: 0 16px 16px 0;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  margin: 32px;
  margin-right: 16px;
}

.logo {
  position: absolute;
  top: 32px;
  left: 32px;
  font-size: 24px;
  color: #409eff;
}

.form-section {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 32px;
  margin: 32px;
  margin-left: 16px;
  background-color: #fff;
  border-radius: 16px 0 0 16px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.form-content {
  width: 100%;
  max-width: 360px;
}

.form-title {
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 24px;
  text-align: center;
  color: #303133;
}

.user-type-select {
  text-align: center;
  margin-bottom: 32px;
}

.user-type-select :deep(.el-radio-button__inner) {
  padding: 8px 24px;
}

.login-form :deep(.el-form-item__label) {
  padding-bottom: 8px;
  font-weight: 500;
}

.login-form :deep(.el-input__wrapper) {
  border-radius: 8px;
}

.remember-options {
  display: flex;
  justify-content: space-between;
  margin-bottom: 24px;
}

.login-button {
  width: 48%;
  margin-top: 24px;
  height: 44px;
  font-size: 16px;
  border-radius: 8px;
}

.register-button {
  width: 48%;
  margin-top: 24px;
  height: 44px;
  font-size: 16px;
  border-radius: 8px;
}

.copyright {
  text-align: center;
  color: #909399;
  font-size: 12px;
  margin-top: 32px;
}
</style>
